#include "ListWidget.h"


#include "Widgets/ButtonWidget.h"
#include "Widgets/RectangleWidget.h"

RListWidget::RListWidget()
{
    Width=468.f;
    Height=270.f;
    bClipSubWidgets=true;
    {   

        ContentPositioner=NewWidget<RVerticalPositionerWidget>(this);   

        ContentPositioner->Spacing=0;
        ContentPositioner->Anchor.LeftReference=this;
        ContentPositioner->Anchor.RightReference=this;   
        ContentPositioner->OnChildrenArranged.Bind(this,&RListWidget::OnContentLengthChanged);
        ContentPositioner->Y=[this]()->float{
            if(ContentPositioner->GetContentPresentLength()<=GetPresentSize().Y)
            {
                return 0;
            }
            else
            {
                return -(ContentPositioner->GetContentPresentLength()-this->GetPresentSize().Y) * ScrollBar->GetCurrentPercent();
            }
        };


        ScrollBar=NewWidget<RScrollBar>(this);
        ScrollBar->Anchor.TopReference=this;
        ScrollBar->Anchor.BottomReference=this;
        ScrollBar->Anchor.RightReference=this;
        //ScrollBar->OnPercentChanged.Bind(this,&RListWidget::OnScrollbarDragged);

    }
}

void RListWidget::ScrollTo(float InPercent)
{

    ScrollBar->SetCurrentPercent(InPercent);
}

void RListWidget::ScrollToTop()
{
    ScrollTo(0.f);
}

void RListWidget::ScrollToBottom()
{
    ScrollTo(1.f);
}

void RListWidget::ScrollToWidget(RWidgetPtr Widget)
{
    if(!Widget)
    {
        return;
    }

    if(Widget->GetParent()!=ContentPositioner)
    {
        return;
    }

    float WidgetHeight=Widget->GetPresentSize().Y;
    if(WidgetHeight==0)
    {
        //may be this widget is new one , not arranged yet
        ContentPositioner->ArrangeChildren();
        WidgetHeight=Widget->GetPresentSize().Y;
    }

    float WidgetY=Widget->GetPresentAbsolutePosition().Y;

    float ListY=ContentPositioner->GetPresentAbsolutePosition().Y;
    float ListHeight=ContentPositioner->GetPresentSize().Y;

    float ScrollPercent=0.f;
    if(WidgetY< ListY)
    {
        ScrollPercent=0.f;
    }
    else if(WidgetY+WidgetHeight>ListY+ListHeight)
    {
        ScrollPercent=1.f;
    }
    else
    {
        ScrollPercent=(WidgetY-ListY)/ListHeight;
    }

    ScrollBar->SetCurrentPercent(ScrollPercent);
}

void RListWidget::OnContentLengthChanged()
{
    ScrollBar->SetSlideWindowLength(this->GetPresentSize().Y);
    ScrollBar->SetContentTotalLength(
        ContentPositioner->GetContentPresentLength()
        ,true
        );
} 

// void RListWidget::OnScrollbarDragged(float NewContentPercent)
// {
//     if(ContentPositioner->GetContentPresentLength()<=this->GetPresentSize().Y)
//     {
//         ContentPositioner->Y=0;
//     }
//     else
//     {
//         ContentPositioner->Y=-(ContentPositioner->GetContentPresentLength()-this->GetPresentSize().Y) * NewContentPercent;
//     }

// } 
